Solve "Cross-Origin Request Blocked" in React frontend to an Express.js API?
Solve "Cross-Origin Request Blocked" in React frontend to an Express.js API?
27503-Aug-2023
Updated on 04-Aug-2023
Home / DeveloperSection / Forums / Solve "Cross-Origin Request Blocked" in React frontend to an Express.js API?
Solve "Cross-Origin Request Blocked" in React frontend to an Express.js API?
Aryan Kumar
04-Aug-2023There are a few ways to solve the cross origin request blocked error in React frontend to an Express.js API.
One way is to use the
Access-Control-Allow-Origin
header in the Express.js API. This header tells the browser that the API is allowed to be accessed from any origin. To do this, you need to add the following header to the response:The
*
wildcard allows requests from any origin. You can also specify a specific origin if you want to restrict access to only that origin.Another way to solve the cross origin request blocked error is to use the
CORS
middleware in Express.js. The CORS middleware automatically adds theAccess-Control-Allow-Origin
header to the response, as well as other headers that are required for cross origin requests. To use the CORS middleware, you need to install thecors
package and then add the following code to your Express.js app:Finally, you can also solve the cross origin request blocked error by using the
proxy
property in the package.json file of your React app. Theproxy
property tells the React app to use a proxy server to make requests to the API. This can be helpful if you are developing your React app locally and the API is running on a different server. To use theproxy
property, you need to add the following line to your package.json file:This line tells the React app to use the proxy server at
http://localhost:3000
to make requests to the API. The proxy server will automatically add theAccess-Control-Allow-Origin
header to the response, so you don't need to worry about adding it yourself.